/**
 * @FileName: StoreSetController.java
 * @Author
 * @Description:
 * @Date 2016年1月6日 下午3:46:52
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.controller.client;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;

import cn.hpclub.server.alipay.AlipayNotify;
import cn.hpclub.server.model.CmccOrder;
import cn.hpclub.server.plugin.Ssdb;

public class AlipayController extends Controller{
    private static Logger log = LoggerFactory.getLogger(AlipayController.class);

    // @ActionKey(value = "pay")
    // public void pay(){
    // HttpServletRequest request = getRequest();
    // log.info("pay notify url:" + request.getRequestURL());
    // log.info("pay notify param:" + request.getParameterMap().toString());
    // }

    @ActionKey(value = "notifyUrl")
    public void payNotify(){

        // log.info("notifyUrl in:");

        HttpServletRequest request = getRequest();
        HttpServletResponse response = getResponse();

        // log.info("pay notify url:" + request.getRequestURL());
        Map<String, String> params = getMapData(request);

        if(AlipayNotify.verify(params)){// 验证成功
            handleOrder(request, response);
        } else{// 验证失败
            log.error("pay notify,verify failed.");
            failed(response);
        }

    }

    /**
     * @Title: failed
     * @Description:TODO
     * @param response
     *            void
     */

    private void failed(HttpServletResponse response){
        log.error("pay notify handle failed.");
        PrintWriter out = null;
        try{
            out = response.getWriter();
            out.println("fail");
        }
        catch(IOException e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally{
            out.flush();
            out.close();
        }
    }

    /**
     * @Title: updateOrder
     * @Description:TODO
     * @param request
     * @param response
     *            void
     */

    private void handleOrder(HttpServletRequest request, HttpServletResponse response){

        String trade_status = "";
        String out_trade_no = "";
        String total_fee = "";
        try{
            out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            total_fee = new String(request.getParameter("total_fee").getBytes("ISO-8859-1"), "UTF-8");
            trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            // log.info("pay,order id:" + out_trade_no + ", total fee:" +
            // total_fee + ", pay status:" + trade_status);
            if(trade_status.equals("TRADE_FINISHED")){
                // log.info("TRADE_FINISHED done");
                succeed(response);
            } else if(trade_status.equals("TRADE_SUCCESS")){
                CmccOrder.dao.updatePayInfo(out_trade_no, 2, new Date(), Double.valueOf(total_fee));
                // log.info("TRADE_SUCCESS done");
                succeed(response);
            } else{
                // log.info("unexcepted status:" + trade_status + " done");
                succeed(response);
            }
        }
        catch(UnsupportedEncodingException e){
            log.error("get pay notify params error.");
            log.error("pay notify order id:" + out_trade_no + ", total fee:" + total_fee + ", pay status:"
                    + trade_status);
            e.printStackTrace();
            failed(response);
        }
        finally{
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            String dateString = simpleDateFormat.format(new Date());

            SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("hh:mm:ss");
            String timeString = simpleDateFormat2.format(new Date());

            Map<String, String> infos = new HashMap<>();
            infos.put("no", out_trade_no);
            infos.put("total", total_fee);
            infos.put("status", trade_status);
            infos.put("time", timeString);
            Ssdb.use().hset(dateString, out_trade_no, infos);
        }

    }

    /**
     * @Title: succeed
     * @Description:TODO
     * @param response
     *            void
     */

    private void succeed(HttpServletResponse response){
        PrintWriter out = null;
        try{
            out = response.getWriter();
            out.println("success"); // 请不要修改或删除
        }
        catch(IOException e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally{
            out.flush();
            out.close();
        }
    }

    /**
     * @Title: getMapData
     * @Description:TODO
     * @param request
     * @return Map<String,String>
     */

    private Map<String, String> getMapData(HttpServletRequest request){

        // 获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();

        // 用于拼接所接收到的参数列表，便于保存
        String queryString = "";
        for(Iterator iter = requestParams.keySet().iterator(); iter.hasNext();){
            String name = (String)iter.next();
            String[] values = (String[])requestParams.get(name);
            String valueStr = "";
            for(int i = 0; i < values.length; i++){
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                queryString += name + "=" + values[i] + "&";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }

        // 去掉最后一个空格
        queryString = queryString.substring(0, queryString.length() - 1);
        // log.info("***********" + "time:" + new Date().toString() +
        // "***********");
        // log.info("params(queryString):" + queryString);

        return params;
    }

}
